from django.shortcuts import render
from rest_framework import mixins
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.views import APIView

from . import constants
from .models import User
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from . import serializers
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet


class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin,GenericViewSet):
    """
    用户收货地址增删改查
    """""
    # 指定序列化器
    serializer_class = serializers.UserAddressSerializer
    # 　指定权限
    permission_classes = [IsAuthenticated]

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """实现地址新增"""""
        # 判断用户地址数量是否超过上线
        # 查询用户的地址
        # count = Address.objects.filter(user=request.user).count()
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)
        # # 创建序列化器
        # serializer = self.get_serializer(data=request.data)
        # # 开启验证
        # serializer.is_valid(raise_exception=True)
        # # 保存数据
        # serializer.save()
        # # 响应结果
        # return Response(serializer.data, status=status.HTTP_201_CREATED)

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


# url(r'^emails/verification/$', views.VerifyEmailView.as_view()),
class VerifyEmailView(APIView):
    """
    邮箱验证
    """""

    def get(self, request):
        # 获取token
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证出token中的user信息(核心代碼)
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message': '链接信息无效'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            # 将user的email_active字段设置为True(核心思想)
            user.email_active = True
            user.save()
            return Response({'message': 'OK'})


#  url(r'^email/$', views.EmailView.as_view()),
class EmailView(UpdateAPIView):
    """
    更新(新建,添加)邮箱
    """""
    serializer_class = serializers.Emailserializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


# url(r'^user/$', views.UserDetailView.as_view()),
class UserDetailView(RetrieveAPIView):
    """
    用户详情
    个人中心基本信息
    """
    # 指定序列化器类
    serializer_class = serializers.UserDetailSerializer
    # 指定权限,只有登陆的用户才可以访问
    permission_classes = [IsAuthenticated]

    # 指定查询集
    # 到目前为止,还没有出现要查询的登陆用户对象信息,如果出现url里面有pk则可以使用queryset = User.objects.all()
    # queryset = User.objects.all()

    # 重写get_object()这样返回的是什么就序列化什么
    """
    class RetrieveModelMixin(object):

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)
    """""

    def get_object(self):
        """重写该方法,返回序列化器要序列化的登陆用户信息"""""
        # 只要视图中加了IsAuthenticated权限,self.request.user出来的结果一定是登陆用户信息
        return self.request.user


# url(r'^users/$', views.UserView.as_view())
class UserView(CreateAPIView):
    """注册"""
    # 　指定序列化器类
    serializer_class = serializers.UserSerializer


# Create your views here.
# url(r'^mobiles/(?P<mobile>1[3-9]\d{9})/count/$', views.MobileCountView.as_view()),
class MobileCountView(APIView):
    """判断用户是否重复登陆"""

    def get(self, request, mobile):
        # 用username作为查询该记录是否存在
        count = User.objects.filter(mobile=mobile).count()

        # 序列化:模型数据转字典
        data = {
            'mobile': mobile,
            'count': count,
        }

        # 响应结果
        return Response(data)


# url(r'^usernames/(?P<username>\w{5,20})/count/$', views.UsernameCountView.as_view()),
class UsernameCountView(APIView):
    """判断用户是否重复登陆"""

    def get(self, request, username):
        # 用username作为查询该记录是否存在
        count = User.objects.filter(username=username).count()

        # 序列化:模型数据转字典
        data = {
            'username': username,
            'count': count,
        }

        # 响应结果
        return Response(data)
